using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;

namespace Zephyris_Space_Mercs
{
    public static class VirtualAccelerometer
    {
        static Accelerometer accelSensor;

        public static Vector3? accelerometerCentre { get; private set; }

        static bool accelActive = false;

        public static void Update()
        {
            if (!accelActive)
            {
                try
                {
                    accelSensor = new Accelerometer();
                    accelSensor.Start();
                    accelSensor.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(accelSensor_CurrentValueChanged);
                    accelActive = true;
                }
                catch (AccelerometerFailedException)
                {
                    accelActive = false;

                    List<string> MBOPTIONS = new List<string>();
                    MBOPTIONS.Add("OK");
                    Guide.BeginShowMessageBox("Accelerometer Error", "The Accelerometer could not be started.", MBOPTIONS, 0, MessageBoxIcon.Error, null, null);
                }
            }
        }

        static void accelSensor_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
        {
            accelerometerCentre = e.SensorReading.Acceleration;
        }

        public static Vector3 AccelerometerValue
        {
            get
            {
                if(!accelerometerCentre.HasValue)
                {
                    return Vector3.Zero;
                }

                Vector3 pos = Vector3.Zero;
                pos = accelerometerCentre.Value;

                pos.Normalize();

                return pos;
            }
        }
    }
}
